<template>
  <el-dialog
    title="关联检测参数"
    :visible.sync="visible"
    width="600px"
    append-to-body
  >
    <el-select
      v-model="selectedGroupId"
      placeholder="请选择参数组"
      style="width: 100%; margin-bottom: 20px;"
    >
      <el-option
        v-for="group in paramGroups"
        :key="group.groupId"
        :label="group.groupName"
        :value="group.groupId"
      ></el-option>
    </el-select>

    <el-tree
      :data="filteredParams"
      :props="treeProps"
      node-key="id"
      @node-click="handleNodeClick"
      show-checkbox
      :default-expand-all="true"
      style="max-height: 300px; overflow-y: auto;"
    ></el-tree>

    <el-form
      :model="paramConfig"
      label-width="100px"
      style="margin-top: 20px;"
      v-if="selectedParam"
    >
      <el-form-item label="表头名称">
        <el-input
          v-model="paramConfig.headerName"
          placeholder="默认：参数名（单位）"
        ></el-input>
      </el-form-item>
      <el-form-item label="数据精度">
        <el-input
          v-model="paramConfig.precision"
          type="number"
          :min="0"
          :max="6"
        ></el-input>
      </el-form-item>
      <el-form-item label="多测量点关联" v-if="selectedParam.isMultiMeasure">
        <el-switch
          v-model="paramConfig.associateAllMeasures"
        ></el-switch>
        <span style="margin-left: 10px;">
          关联所有{{ selectedParam.multiMeasureCount }}个测量点
        </span>
      </el-form-item>
    </el-form>

    <div slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="confirmAssociate">确认关联</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { getParamConfig } from '@/mock/paramConfig';

export default {
  name: 'ParamSelector',
  props: {
    currentCell: {
      type: Object,
      required: true
    }
  },
  data() {
    return {
      visible: false,
      paramGroups: [],
      treeProps: {
        label: 'name',
        children: 'children'
      },
      selectedGroupId: '',
      selectedParam: null,
      paramConfig: {
        headerName: '',
        precision: 1,
        associateAllMeasures: true
      }
    };
  },
  computed: {
    // 过滤选中参数组的参数
    filteredParams() {
      if (!this.selectedGroupId) {
        return this.formatParamTree(this.paramGroups);
      }
      const selectedGroup = this.paramGroups.find(
        group => group.groupId === this.selectedGroupId
      );
      return selectedGroup ? this.formatParamTree([selectedGroup]) : [];
    }
  },
  methods: {
    // 打开弹窗
    open() {
      this.initParamGroups();
      this.visible = true;
    },
    // 初始化参数组（格式化树形结构）
    initParamGroups() {
      this.$loading({ text: '加载参数配置...' });
      getParamConfig().then((res) => {
        this.$loading().close();
        if (res.code === 200) {
          this.paramGroups = res.data.paramGroups;
        }
      });
    },
    // 格式化参数组为树形结构（适配el-tree）
    formatParamTree(groups) {
      return groups.map(group => {
        const groupNode = {
          id: group.groupId,
          name: group.groupName,
          type: 'group',
          children: []
        };
        // 嵌套组：子组作为子节点
        if (group.isNested && group.childGroups.length > 0) {
          groupNode.children = this.formatParamTree(group.childGroups);
        } else {
          // 非嵌套组：参数作为子节点
          groupNode.children = group.paramItems.map(param => ({
            id: param.paramId,
            name: `${param.paramName}${param.unit ? '（' + param.unit + '）' : ''}`,
            type: 'param',
            ...param
          }));
        }
        return groupNode;
      });
    },
    // 点击树节点
    handleNodeClick(node) {
      if (node.type === 'param') {
        this.selectedParam = node;
        // 初始化配置
        this.paramConfig.headerName = node.name;
        this.paramConfig.precision = node.precision || 1;
      } else {
        this.selectedParam = null;
      }
    },
    // 确认关联
    confirmAssociate() {
      if (!this.selectedParam) {
        this.$message.warning('请选择要关联的参数');
        return;
      }
      // 构建关联规则
      const associateRule = {
        cellRow: this.currentCell.row,
        cellCol: this.currentCell.col,
        paramId: this.selectedParam.paramId,
        groupId: this.selectedGroupId,
        headerName: this.paramConfig.headerName,
        precision: this.paramConfig.precision,
        isMultiMeasure: this.selectedParam.isMultiMeasure,
        multiMeasureCount: this.selectedParam.isMultiMeasure ? this.selectedParam.multiMeasureCount : 1,
        associateAllMeasures: this.paramConfig.associateAllMeasures
      };
      this.$emit('associate-success', associateRule);
      this.visible = false;
    }
  }
};
</script>